package cn.exrick.xboot.modules.transport.controller;

import cn.exrick.xboot.common.exception.XbootException;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.base.enums.OrderStatusEnum;
import cn.exrick.xboot.modules.transport.entity.OrderCarInfo;
import cn.exrick.xboot.modules.transport.entity.Orders;
import cn.exrick.xboot.modules.transport.gps.dto.GpsFindDevRequest;
import cn.exrick.xboot.modules.transport.gps.dto.GpsFindDevResponse;
import cn.exrick.xboot.modules.transport.gps.dto.GpsQueryLocationRequest;
import cn.exrick.xboot.modules.transport.gps.dto.GpsQueryLocationResponse;
import cn.exrick.xboot.modules.transport.gps.service.GpsApiService;
import cn.exrick.xboot.modules.transport.mapper.OrderCarInfoMapper;
import cn.exrick.xboot.modules.transport.mapper.OrdersMapper;
import cn.exrick.xboot.modules.transport.vo.RealTimePositioningVo;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * @author gj
 */
@Slf4j
@RestController
@Api(tags = "第三方GPS对接信息管理接口")
@RequestMapping("/xboot/thirdPartyGps")
@Transactional
public class ThirdPartyGpsController {

    @Autowired
    private GpsApiService gpsApiService;
    @Autowired
    private OrderCarInfoMapper orderCarInfoMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    @RequestMapping(value = "/getRealTimePositioning/{orderCarInfoId}", method = RequestMethod.GET)
    @ApiOperation(value = "获取订单车辆实时坐标")
    public Result<RealTimePositioningVo> getRealTimePositioning(@PathVariable Long orderCarInfoId) {
        RealTimePositioningVo realTimePositioningVo = new RealTimePositioningVo();

        //根据orderCarInfo 查询订单，如果订单已到达，则获取 orderCarInfo中的轨迹坐标的最后一个点
        // 若未到达，则查询 GPS 对接表，获取最近的 GPS 轨迹点
        OrderCarInfo orderCarInfo = orderCarInfoMapper.selectById(orderCarInfoId);
        if(ObjectUtil.isEmpty(orderCarInfo)){
            throw new XbootException("车辆信息不存在");
        }
        Orders order = ordersMapper.selectById(orderCarInfo.getOrderId());
        realTimePositioningVo.setOrderCarInfoId(orderCarInfoId);
        realTimePositioningVo.setGpsImei(orderCarInfo.getGpsImei());
        //如果订单状态为arrived、received、completed 则获取 orderCarInfo中的轨迹坐标的最后一个点
        if (order.getStatus().equals(OrderStatusEnum.Arrived.getValue())
                || order.getStatus().equals(OrderStatusEnum.Received.getValue())
                || order.getStatus().equals(OrderStatusEnum.Completed.getValue())) {
            // 获取 orderCarInfo中的坐标的最后一个点
            String gpsLocation = orderCarInfo.getGpsLocation();
            if (StrUtil.isNotBlank(gpsLocation)){
                String[] locations = gpsLocation.split(" \\|");
                String location = locations[locations.length - 1];
                String[] latLon = location.split(",");
                realTimePositioningVo.setLat(latLon[0]);
                realTimePositioningVo.setLon(latLon[1]);
            }

        } else if (order.getStatus().equals(OrderStatusEnum.Accepted.getValue())
                || order.getStatus().equals(OrderStatusEnum.InTransit.getValue())
                || order.getStatus().equals(OrderStatusEnum.Transferring.getValue())){

            GpsFindDevRequest gpsFindDevRequest = new GpsFindDevRequest();
            gpsFindDevRequest.getParams().setImei(orderCarInfo.getGpsImei());
            List<GpsFindDevResponse> devices = gpsApiService.findDevices(gpsFindDevRequest);
            if (CollectionUtil.isNotEmpty(devices)) {
                GpsQueryLocationRequest gpsQueryLocationRequest = new GpsQueryLocationRequest();
                gpsQueryLocationRequest.getParams().setSimei(devices.get(devices.size() - 1).getSimei());
                ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
                gpsQueryLocationRequest.getParams().setTime_begin(order.getAcceptanceTime().atZone(shanghaiZone).toEpochSecond());
                gpsQueryLocationRequest.getParams().setTime_end(LocalDateTime.now().atZone(shanghaiZone).toEpochSecond());
                List<GpsQueryLocationResponse> gpsQueryLocationResponses = gpsApiService.queryLocation(gpsQueryLocationRequest);
                if (CollectionUtil.isNotEmpty(gpsQueryLocationResponses)) {
                    GpsQueryLocationResponse gpsQueryLocationResponse = gpsQueryLocationResponses.get(gpsQueryLocationResponses.size() - 1);
                    realTimePositioningVo.setLat(gpsQueryLocationResponse.getLat().toString());
                    realTimePositioningVo.setLon(gpsQueryLocationResponse.getLon().toString());
                }
            }
        }
        return new ResultUtil<RealTimePositioningVo>().setData(realTimePositioningVo);
    }

    @RequestMapping(value = "/findDevices/{imei}", method = RequestMethod.GET)
    @ApiOperation(value = "获取车辆gps信息")
    public Result<GpsFindDevResponse> get(@PathVariable Long imei) {
        GpsFindDevRequest gpsFindDevRequest = new GpsFindDevRequest();
        gpsFindDevRequest.getParams().setImei(imei.toString());
        List<GpsFindDevResponse> devices = gpsApiService.findDevices(gpsFindDevRequest);
        return new ResultUtil<GpsFindDevResponse>().setData(devices.get(devices.size() - 1));
    }

}
